<?php
class NewsController extends AppController {
	public $name = 'News';
	public $uses=array('News','NewsCategory','FriendlyUrl');
	function admin_index($pid=0){
		//get filter field
		$filterField=array(
			'I18n__title.content'=>_resource('title',true),
		'I18n__description.content'=>_resource('description',true),
		'I18n__content.content'=>_resource('content',true)
		);
		$this->{$this->uses[1]}->locale=$this->Session->read('adminLang');
		$this->set('filterField',$filterField);
		//set list cac country name ra view
		if($this->webConfig['is_multi_lang'])
		$this->set('listLang',$this->Common->listCountry());
		//===================================================================
		$pid=intval($pid);
		if($pid)
		{
			//get list cat:
			$parent=$this->{$this->uses[1]}->findById($pid);
			$datacat='';
			if(!empty($parent))$datacat=$this->{$this->uses[1]}->find('list',array('conditions'=>array($this->uses[1].'.parent_id'=>$parent[$this->uses[1]]['parent_id']),'fields'=>array($this->uses[1].'.id',$this->uses[1].'.title')));
			$this->set('datacat',$datacat);
		}
		//get all cat
		else{
				
			$this->set('datacat',$this->getallcat());
		}
		$this->set('pid',$pid);
		$this->set('pname',$parent[$this->uses[1]]['title']);
		$this->render('admin_index','ajax');
	}

	function admin_lists($pid=0){
		//khoi tao cac session can thiet cho 1 model, session nay dung de luu lai trang thai cua 1 model nhu phan trang, sort tang giam, dieu kien search, id cha...
		//cac su dung Session cua cakephp : doc them trong book.cakephp.org
		if(!$this->Session->check($this->uses[0])){
			//khoi tao array vao bien $tmp
			$tmp=array(
				'limit'=>$this->webConfig['default_row_per_page'],
				'conditions'=>'',
				'fields'=>null,
				'order'=>$this->uses[0].'.id desc',
				'page'=>1,
				'recursive'=>0,
				'sortField'=>null,
				'sortDir'=>'asc',				
				'filterField'=>'',
				'filterText'=>'',
				'catid'=>'',
			);
			//luu vao session
			$this->Session->write($this->uses[0],$tmp);
		}


		$this->{$this->uses[0]}->locale=$this->Session->read('adminLang');
		//doc ra cac trang thai cua 1 model da luu trong session
		// truyen vao bien paginate, khi lay data, model se dua vao cac gia tri cua bien nay de search, sort, phan trang ...
		$paginate=$this->Session->read($this->uses[0]);
		$pid=intval($pid);
		$rootcatname='';
		if($pid){
			$paginate['conditions'][$this->uses[0].'.parent_id']=$pid;
			//get root cat
			$cat=$this->{$this->uses[1]}->find('first',array('conditions'=>array($this->uses[1].'.id'=>$pid)));
			if(!empty($cat)){
				$datacat=$this->{$this->uses[1]}->find('first',array('conditions'=>array($this->uses[1].'.id'=>$cat[$this->uses[1]]['parent_id']),'fields'=>array($this->uses[1].'.title')));
				$rootcatname=$datacat[$this->uses[1]]['title'];
			}
		}
		$this->paginate=$paginate;
		//ham paginate() la ham ho tro phan trang, khi dung ham nay, se tu dong phan trang theo cac gia tri trong bien paginate o tren
		//lay data da duoc phan trang va truyen vao bien $data0
		$data0=$this->paginate($this->uses[0]);
		
		//t($data0);
		//su dung khi site co chuc nang da ngon ngu==========================
		//duyet qua tat ca cac rows trong $data0 de kiem tra xem data cua rows da co ngon ngu nao roi.
		if($this->webConfig['is_multi_lang']){
			foreach($data0 as $k=>$v){
				$data0[$k]['Langs']=$this->getLangs($v[$this->uses[0]]['id'],$this->uses[0]);
			}
			$this->set('listLang',$this->Common->listCountry());
		}		
		//===================================================================
		//set bien $data0 ra view de hien ra luoi.

		$this->set('data0',$data0);
		$this->set('rootcatname',$rootcatname);
		$this->set('pid',$pid);

		//render view va cho cakephp biet day la view cua ajax -> khi do, cakephp se chi render view ma khong render toan bo layout cua website.
		$this->render('admin_lists','ajax');
	}

	function admin_add($pid=0,$locale=null){
		//su dung khi site co chuc nang da ngon ngu==========================
		//neu khong truyen vao ngon ngu thi ngon ngu mac dinh cua data duoc them vao se la ngon ngu duoc doc tu session
		if(!$locale){
			$locale=$this->Session->read('adminLang');
		}
		//khai bao ngon ngu cua model, khi do, ngon ngu cua data duoc luu vao database la $locale
		$this->{$this->uses[0]}->locale=$locale;
		//====================================================================
		$this->{$this->uses[0]}->recursive=0;
		$name_error=_resource('can not be null',true);
		$isInsert=false;
		if(!empty($this->data)){
			if($this->{$this->uses[0]}->create($this->data) && $this->{$this->uses[0]}->validates()){
				if($this->{$this->uses[0]}->save($this->data)) {
					//================seo link add
					$lastinsertId=$this->{$this->uses[0]}->getLastInsertID();
					if(intval($this->data[$this->uses[0]]['parent_id'])>0){
						//get parent name:
						$parent=$this->{$this->uses[1]}->findById(intval($this->data[$this->uses[0]]['parent_id']));
						$parent=$this->{$this->uses[1]}->findById(intval($parent[$this->uses[1]]['parent_id']));
						if(!empty($parent))$this->updateSeoLink('/'.$parent[$this->uses[1]]['title'].'/detail/'.$lastinsertId.'/'.$locale, $this->data[$this->uses[0]]['title'], $lastinsertId,$this->uses[0]);
					}
					$this->Common->updateCacheRoute(false);
					//=======================
					$this->data=null;
					$isInsert=true;
					$this->Session->write('message',_resource('insert data successful',true));
				} else {
					$this->Session->write('error',_resource('can not insert data',true));
				}
			}else{
				$this->Session->write('error',_resource('red fill is require',true));
			}
		}

		//======================
		//set bien locale ra view de su dung
		$this->set('locale',$locale);
		$this->set('pid',$pid);
		if($this->webConfig['is_multi_lang'])
		$this->set('listLang',$this->Common->listCountry());

		$this->set('isInsert',$isInsert);
		$this->set('name_error',$name_error);
	}

	function admin_edit($id=null,$pid=0,$locale=null){
		if(!$locale){
			$locale=$this->Session->read('adminLang');
		}
		$this->{$this->uses[0]}->locale=$locale;
		$name_error=_resource('can not be null',true);
		$isInsert=false;
		$this->{$this->uses[0]}->recursive=0;
		if(!empty($this->data)){
			//t($this->data);
			if($this->{$this->uses[0]}->create($this->data) && $this->{$this->uses[0]}->validates()){
				if($this->{$this->uses[0]}->save($this->data)) {
						
					//=================seo link update
					if(intval($this->data[$this->uses[0]]['parent_id'])>0){
						//get parent name:
						$parent=$this->{$this->uses[1]}->findById(intval($this->data[$this->uses[0]]['parent_id']));
						$parent=$this->{$this->uses[1]}->findById(intval($parent[$this->uses[1]]['parent_id']));
						if(!empty($parent))$this->updateSeoLink('/'.$parent[$this->uses[1]]['title'].'/detail/'.$this->data[$this->uses[0]]['id'].'/'.$locale, $this->data[$this->uses[0]]['title'], $this->data[$this->uses[0]]['id'],$this->uses[0]);
					}
						
					$this->Common->updateCacheRoute(false);
					//update cache
					//=======================================
						

					$this->data=null;
					$isInsert=true;
					$this->Session->write('message',_resource('update data successful',true));
				} else {
					$this->Session->write('error',_resource('can not update data',true));
				}
			}else{
				$this->Session->write('error',_resource('red fill is require',true));
			}
		}else{
			if($id!=null){

				//get data from default language
				if($this->{$this->uses[0]}->locale!=$this->Session->read('adminLang') && $this->webConfig['is_multi_lang']){
					$this->{$this->uses[0]}->locale=$this->Session->read('adminLang');
					$defaultdata =$this->{$this->uses[0]}->read(null,$id);
					//t($this->data);
					$this->{$this->uses[0]}->locale=$locale;
					$data =$this->{$this->uses[0]}->read(null,$id);
						
					//get data of current select language
					foreach($this->{$this->uses[0]}->actsAs['Translate'] as $k=>$v){
						$defaultdata[$this->uses[0]]['default'.$v]=$defaultdata[$this->uses[0]][$v];
						$defaultdata[$this->uses[0]][$v]=$data[$this->uses[0]][$v];
					}
					$data=$defaultdata;
				}
				else{
						
					$data =$this->{$this->uses[0]}->read(null,$id);
						
				}
				$data[$this->uses[0]]['oldimage']=$data[$this->uses[0]]['image'];
				$this->data=$data;
				
				if(empty($this->data)){
					$this->Session->write('error',_resource('data not found',true));
					$this->render('admin_editNotFound');
				}
			}
			else{
				$this->Session->write('error',_resource('data not found',true));
				$this->render('admin_edit_not_found');
			}
		}


		//get cat
		$this->set('datacat',$this->getallcat());
		//set bien locale ra view de su dung
		$this->set('locale',$locale);
		$this->set('pid',$pid);
		if($this->webConfig['is_multi_lang'])
		$this->set('listLang',$this->Common->listCountry());

		$this->set('isInsert',$isInsert);
		$this->set('name_error',$name_error);

	}

	function admin_delete($pid=0,$id = null) {
		$this->Session->delete('error');
		//if is submit:
		if($this->request->is('post')){
			$id_arr=$this->data['check'];
		} else {
			$id_arr=null;
		}
		//if url
		if(intval($id)){
			$id_arr[$id]='';
		}
		if(count($id_arr)>0){
			//Xoa nhieu record
			foreach($id_arr as $k=>$v)$this->{$this->uses[0]}->delete($k);	
		} else {
			$this->Session->write('error',_resource('no information to delete',true));
		}
		$this->admin_lists();
	}

	function admin_published($id=null,$value=1,$field=0,$pid=0){
		$id_arr=null;
		$all=false;
		switch($field){
			case 1: $fieldname='home';$title='showed in home page';break;
			case 2: $fieldname='important';$title='showed on top';break;
			default: $fieldname='published';$title='published';
		}
		if((!intval($value) && $value!=0) || intval($value)>1){
			$value=1;
		}

		//if is submit:
		if($this->request->is('post')){
			$id_arr=$this->data['check'];
			$all=true;
		}

		//if url
		if(intval($id) && !$all){
			$id_arr[$id]='';
		}

		if(count($id_arr)>0){
			$this->{$this->uses[0]}->query('update '.$this->{$this->uses[0]}->tablePrefix.$this->{$this->uses[0]}->table.' set '.$fieldname.'='.$value.' where id in ('.implode(',',array_keys($id_arr)).')' );
		}
		if (!$all) {
			$this->set('value',$value);
			$this->set('field',$field);
			$this->set('fieldname',$fieldname);
			$this->set('title',$title);
			$this->set('id',intval($id));
			$this->render('admin_published','ajax');
		} else {
			$this->admin_lists($pid);
		}

	}

	function admin_sort($sortField=null,$sortDir='asc',$pid=0){
		if($sortField){
			if($sortDir!='desc') $sortDir='asc';
			$this->Session->write($this->uses[0].'.sortField',$sortField);
			$this->Session->write($this->uses[0].'.sortDir',$sortDir);
			$this->Session->write($this->uses[0].'.order',$sortField.' '.$sortDir);
		}
		$this->admin_lists($pid);
	}

	function admin_page($page=1,$pid=0){
		$this->Session->write($this->uses[0].'.page',$page);
		$this->admin_lists($pid);
	}

	function admin_display($pid=0,$limit=0){
		if(intval($limit)){
			$this->Session->write($this->uses[0].'.limit',$limit);
		}
		$this->admin_lists($pid);
	}

	function admin_filter($pid=0){
		if($this->request->is('post')){
			$this->Session->write($this->uses[0].'.filterText',$this->request->data['filter_text']);
			$this->Session->write($this->uses[0].'.filterField',$this->request->data['filter_field']);
			//$conditions=$this->Session->read($this->uses[0].'.conditions');
			if(!empty($this->request->data['filter_text'])){
				$conditions[$this->request->data['filter_field'].' like']='%'.$this->request->data['filter_text'].'%';
				$this->Session->write($this->uses[0].'.page',1);
			}
			else{
				unset($conditions[$this->request->data['filter_field'].' like']);
			}
				
			$this->Session->write($this->uses[0].'.conditions',$conditions);
		}
		$this->admin_lists($pid);
	}



	/*
	 * ham dung khi co su dung chuc nang da ngon ngu
	 * dung de change locale cua he thong
	 * tham so truyen vao la locale cua ngon ngu
	 */
	function admin_changeLocale($locale=null,$pid=0){
		//luu session
		if($locale){
			$this->Session->write('adminLang',$locale);
		}
		//reload lai luoi de apply locale vua change
		$this->admin_lists($pid);
	}

	function getallcat(){
		$cats=array();
		$allcats=$this->{$this->uses[1]}->find('list',array('conditions'=>$this->uses[1].'.parent_id=0','fields'=>array('id','title')));
		foreach($allcats as $k=>$v){
			$cats[$k]=$v;
			$subcats=$this->{$this->uses[1]}->find('list',array('conditions'=>$this->uses[1].'.parent_id='.$k,'fields'=>array('id','title')));
			foreach($subcats as $k2=>$v2)$cats[$k2]='__'.$v2;
		}
		return $cats;
	}

	function index($page=1){
		$this->layout='default';
		$this->set('css','news');
		$this->set('title_for_layout','Tin tức SCY');
		if(!$this->Session->check($this->uses[0])){
			//khoi tao array vao bien $tmp
			$tmp=array(
				'limit'=>$this->webConfig['news_per_page'],
				'conditions'=>'',
				'fields'=>null,
				'order'=>$this->uses[0].'.id desc',
				'page'=>1,
				'recursive'=>0,
				'sortField'=>null,
				'sortDir'=>'asc',				
				'filterField'=>'',
				'filterText'=>'',
				'catid'=>'',
			);
			//luu vao session
			$this->Session->write($this->uses[0],$tmp);
		}
		if(intval($page)>0)$this->Session->write($this->uses[0].'.page',$page);
		//get top new
		$datatop=$this->{$this->uses[0]}->find('first',array('conditions'=>'News.published=1','order'=>'News.important desc, News.id desc'));
		$this->set('datatop',$datatop);


		$conditions['News.id <>']=$datatop[$this->uses[0]]['id'];
		$conditions['News.published']=1;
		$this->Session->write($this->uses[0].'.conditions',$conditions);

		$this->{$this->uses[0]}->locale=$this->Session->read('siteLang');
		//doc ra cac trang thai cua 1 model da luu trong session
		// truyen vao bien paginate, khi lay data, model se dua vao cac gia tri cua bien nay de search, sort, phan trang ...

		$this->paginate=$this->Session->read($this->uses[0]);
			


		//ham paginate() la ham ho tro phan trang, khi dung ham nay, se tu dong phan trang theo cac gia tri trong bien paginate o tren
		//lay data da duoc phan trang va truyen vao bien $data0
		$data0=$this->paginate($this->uses[0]);
		//t($data0);

		//set bien $data0 ra view de hien ra luoi.
		$this->set('data0',$data0);


	}

	function detail($id=null){
		$this->layout='default';

		$this->set('css','newsdetail');
		$this->{$this->uses[0]}->locale=$this->Session->read('siteLang');
		$id=intval($id);


		$data=$this->{$this->uses[0]}->find('first',array('conditions'=>'News.id='.$id.' and News.published=1'));
		if(isset($data[$this->uses[0]]['id'])){
			$this->set('title_for_layout',$data['News']['title']);
			//meta for fb
			$this->set('ogTitle',$data[$this->uses[0]]['title']);
			if($data[$this->uses[0]]['activity'])$this->set('ogType','scyclub:activity');
			else $this->set('ogType','article');
			$this->set('ogDescription',$data['News']['description']);
			$this->set('ogUrl','/news/detail/'.$data['News']['id']);
			$this->set('ogImage',SITE_URL.'/uploaded/News/thumb/'.$data['News']['image']);
			$this->set('data',$data);
			$data0=$this->{$this->uses[0]}->find('all',array('conditions'=>'News.id<>'.$id.' and News.published=1','order'=>'News.id desc','limit'=>$this->webConfig['orther_news_page']));
			//set bien $data0 ra view de hien ra luoi.
				
			//donate info
			if($data['News']['donate']){
				$donate=$this->StaticPage->findByKeycode('donate');
				if(isset($donate['StaticPage']['content']))$donate=$donate['StaticPage']['content'];
				$this->set('donate',$donate);
			}
				
			$this->set('data0',$data0);
		}
		else{
			$this->redirect('/news');
		}



		//t($uid);

	}



}
?>
